<template>
    <rx-dialog @handOk="onSave(true)" @cancel="cancel" btnalign="right" order="top">
        <template #toolbar>
            <a-button type="primary" @click="onSave(false)">{{i18n('list.designTem','设计模板')}}</a-button>
        </template>
        <a-form :form="form">
            <a-form-item style="display:none">
                <a-input v-decorator="['id']"/>
                <a-input v-decorator="['templateId']"/>
            </a-form-item>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$ti18('rxForm.name','名称')">
                        <a-input :placeholder="$ti18('rxForm.name','名称','','input')" v-decorator="['name']"/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.temName','模版名称')">
                        <a-input :placeholder="i18n('form.temName','模版名称')" v-decorator="['templateName']"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="$ti18('rxForm.describe','描述')">
                        <a-textarea :placeholder="$ti18('rxForm.describe','描述')" v-decorator="['description']" :rows="4"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$ti18('rxForm.type','类型')">
                        <a-select v-model="type" :options="typeAry"/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item v-show="type=='boDef'" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.boDefine','BO定义')">
                        <rx-input-button width="100%" @click="openBoDef"
                                         v-decorator="['boDefId',{rules:[{required:type=='boDef',message:i18n('notNull','不能为空')}]}]"
                        ></rx-input-button>
                    </a-form-item>
                    <a-form-item v-show="type=='sql'" :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.dataSource','数据源')">
                        <rx-input-button style="width: 100%;margin-top: 6px;" @click="openDataSource"
                                         v-decorator="['dsAlias']"></rx-input-button>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row v-if="type=='sql'">
                <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" label="SQL">
                        <div class="table-operator">
                            <a-button @click="addRow">{{$ti18('rxList.newBtn','添加')}}</a-button>
                            <a-button @click="insertPk">{{i18n('list.insertKey','插入主键')}}</a-button>
                        </div>
                        <table spacing="1" cellspacing="0" cellpadding="0" id="sqlTable" class="table-view">
                            <col style="width: 20%;min-width: 200px;"/>
                            <col style="width: 60%"/>
                            <col style="width: 20%;min-width: 200px;"/>
                            <thead>
                            <tr>
                                <th>{{i18n('list.tableType','表类型')}}</th>
                                <th>{{i18n('list.sqlSet','SQL语句设置')}}</th>
                            </tr>
                            </thead>
                            <tbody id="tbodySql">
                            <tr>
                                <td style="text-align: center">main</td>
                                <td>
                                    <rx-monaco-editor
                                        @focus="onSelect('mainSql')"
                                        ref="mainSql"
                                        v-model="mainSql"
                                        language="sql"
                                        style="height:150px;width: 100%;"
                                    >
                                    </rx-monaco-editor>
                                </td>
                            </tr>
                            <tr class="tbodySqltr" v-for="(item, idx)  in subAry">
                                <td style="text-align: center">
                                    <a-input v-model="item.name"/>
                                </td>
                                <td>
                                    <div class="form-toolBox">
                                        {{i18n('list.relateType','关系类型')}}:
                                        <a-select v-model="item.type" :options="relTypeAry" style="width:80px;"/>
                                        <a-button @click="deleteRow(idx)">{{$ti18('rxList.delBtn','删除')}}</a-button>
                                    </div>
                                    <rx-monaco-editor
                                        @focus="onSelect('sbuSql_'+idx)"
                                        :ref="'sbuSql_'+idx"
                                        v-model="item.sql"
                                        language="sql"
                                        style="height:150px;width: 100%;"
                                    >
                                    </rx-monaco-editor>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </rx-dialog>
</template>
<script>
    import SysWordTemplateApi from '@/api/system/core/sysWordTemplate'
    import {Util, BaseForm, Dialog, RxDialog, RxInputButton, RxMonacoEditor,JsConstant,TokenUtil} from "@lowcode/jpaas-common-lib";
    import {ntkoBrowser} from "@/components/iweboffice/officecontrol/ntkobackground.min.js";
    import AppName from "@/assets/js/AppName.js";

    export default {
        name: 'SysWordTemplateEdit',
        mixins: [BaseForm,AppName],
        components: {
            RxDialog,
            RxInputButton,
            RxMonacoEditor
        },
        data() {
            return {
                onDataFun: "OnData_" + Util.randomId(),
                complexJson: {
                    main: {
                        dsAlias: {text: "dsName", value: "dsAlias"},
                        boDefId: {text: "boDefName", value: "boDefId"}
                    }
                },
                type: 'boDef',
                typeAry: [{label: this.i18n('form.boDefine','BO定义'), value: 'boDef'},
                    {label: 'SQL', value: 'sql'}],
                relTypeAry: [{label: this.i18n('oneToOne','一对一'), value: 'onetoone'},
                    {label: this.i18n('oneToMany','一对多'), value: 'onetomany'}],
                mainSql: '',
                subAry: [],
                selectCtl: ""
            }
        },
        created() {
            var self_ = this;
            eventBus.$off(this.onDataFun);
            eventBus.$on(this.onDataFun, (officeObjStr) => {
                self_.setOffice(officeObjStr);
            });
        },
        // 实例销毁前
        beforeDestroy() {
            // 避免重复监听，页面销毁时销毁监听
            eventBus.$off(this.onDataFun);
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "sysWordTemplate", key);
            },
            setOffice(officeObjStr) {
                var officeJson = JSON.parse(officeObjStr);
                this.form.setFieldsValue({'templateId': officeJson.officeId, templateName: officeJson.docName})
            },
            onload_(values) {
                if (values) {
                    this.type = values.type;
                    if (values.setting) {
                        var setting = JSON.parse(values.setting);
                        this.mainSql = setting.main;
                        this.subAry = setting.sub;
                    }
                }
            },
            get(id) {
                return SysWordTemplateApi.get(id);
            },
            save(values) {
                values.type = this.type;
                values.setting = JSON.stringify({main: this.mainSql, sub: this.subAry});
                return SysWordTemplateApi.save(values);
            },
            addRow() {
                this.subAry.push({name: "", type: "onetomany", sql: "select * from "});
            },
            deleteRow(idx) {
                this.subAry.splice(idx, 1);
            },
            insertPk() {
                if (!this.selectCtl) return;
                var ctl;
                if (this.selectCtl == 'mainSql') {
                    ctl = this.$refs[this.selectCtl];
                } else {
                    ctl = this.$refs[this.selectCtl][0];
                }
                ctl.insertContent('${pk}');
            },
            onSelect(ctl) {
                this.selectCtl = ctl;
            },
            openDataSource(vm) {
                Dialog.openDataSourceDialog({
                    curVm: this, widthHeight: ['800px', '600px'],
                    data: {appName: this.serviceName}
                }, function (self, data) {
                    vm.setVal(data.alias, data.name);
                })
            },
            openBoDef(vm) {
                var self = this;
                Dialog.openBoDefDialog({
                    curVm: this, widthHeight: ['800px', '600px']
                }, function (data) {
                    vm.setVal(data.id, data.name)
                })
            },
            goToOffice(values) {
                let ntkoed = ntkoBrowser.ExtensionInstalled(); //判断插件是否安装
                var accessToken = TokenUtil.getToken();
                if (ntkoed) {
                    var url = "/office/ntkoofficefields?pkId=" + values.pkId;
                    url = url + "&isversion=false" +
                        "&officeId=" + (values.templateId ? values.templateId : "") +
                        "&docName=" + (values.templateName ? values.templateName : "") +
                        "&accessToken=" + accessToken +
                        "&onDataFun=" + this.onDataFun;
                    ntkoBrowser.openWindow(url, true);
                }
            },
            onSave(onlySave) {

                this.form.validateFields((err, values) => {
                    if (err) {
                        return;
                    }
                    values.pkId = this.pkId;
                    this.confirmLoading = true;
                    if (this.validForm) {
                        var flag = this.validForm(values);
                        if (!flag) {
                            return;
                        }
                    }
                    this.onSubmit(values);
                    this.save(values).then(res => {
                        if (res.success && res.code == 200) {
                            //返回结果数据。
                            this.resultData = res.data;
                            if (!onlySave) {
                                this.form.setFieldsValue({'id': this.resultData.pkId});
                                this.goToOffice(res.data);
                            } else {
                                Util.closeWindow(this, "ok");
                            }
                        }
                    }).catch(() => {
                        this.$message.error(this.$ti18('rxMsa.sysError','系统错误，请稍后再试!'))
                    }).finally(() => {
                        this.confirmLoading = false
                    })
                })
            }
        }
    }
</script>
<style scoped>
    .table-view {
        width: 100%;
        border-collapse: collapse;
        border: none;
        margin: 0 auto;
    }

    .table-view .tab {
        border: dotted 1px #ccc;
    }

    .table-view > tbody > tr > td {
        border: solid #ececec 1px;
        padding: 4px;
    }

    .table-view > tbody > tr > th {
        border: solid #ececec 1px;
        padding: 4px;
        white-space: nowrap;
    }

    .table-view > thead > tr > td {
        border: solid #ccc 1px;
        padding: 4px;
        white-space: nowrap;
    }

    .table-view > thead > tr > th {
        border: solid #ccc 1px;
        padding: 4px;
    }
</style>
